//
//  KLDelegateCommondTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/6/8.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLDelegateCommondTableViewController.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "HemaFunction.h"
#import "JRToast.h"
#import "KLHttpAPI.h"
#import "Masonry.h"
#import "IdentifierValidator.h"
#import "DateViewController.h"
#import "CalenderView.h"
#import "BuleFuction.h"
#import "SSKeychain.h"
#import "NSData+hex.h"
#import "BeeCloud+Utils.h"
#import "KLRechargeViewController.h"
#import "UIAlertView+Blocks.h"
#import "HemaFunction.h"
#import "WSDatePickerView.h"

@interface KLDelegateCommondTableViewController () <UITextFieldDelegate,UIAlertViewDelegate,UIActionSheetDelegate,BeeCloudDelegate>
{
    NSDictionary *publicKeysDic; //keychain里的公钥集
    NSString *totalfee;
}
@property (nonatomic,strong) UITextField *delegatePhone;
@property (nonatomic,strong) UIButton *beginTimeBtn;//起始时间按钮
@property (nonatomic,strong) UIButton *endTimeBtn;//结束时间按钮

@property (nonatomic,strong) NSString *beginTimeToLock;
@property (nonatomic,strong) NSString *endTimeToLock;

@property (nonatomic,strong) NSString *money; //在线支付的钱数
@property (nonatomic,strong) NSString *trade_no; //支付订单号
@end

@implementation KLDelegateCommondTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发放委托命令";
    //设置主界面
    [self mainUiSet];
    //获取keychain里的所有公钥
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    publicKeysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    
    NSLog(@"显示当前锁信息:%@",self.currentLockInfo);
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"delegateCommond"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.section == 0){
        cell.textLabel.text = @"校时";
    }else if (indexPath.section == 1){
        cell.textLabel.text = @"设置黑名单";
    }else if (indexPath.section == 2){
        cell.textLabel.text = @"取消黑名单";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.tableView endEditing:YES];
    NSString *myselfPhone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
    if([myselfPhone isEqualToString:self.delegatePhone.text]){
        [JRToast showWithText:@"锁主无法自我委托！"];
        return ;
    }
    
    if([IdentifierValidator isValid:IdentifierTypePhone value:self.delegatePhone.text]){
        if(self.beginTimeToLock.length == 0 || self.endTimeToLock.length == 0){
            [JRToast showWithText:@"请选择指令有效期!"];
            return;
        }
        
        if(self.isFirstMaster){
            NSString *rsaKey = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
            if(rsaKey == nil){
                [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
                return ;
            }
            NSString *aesKey = [KLHelp getUserSixTeenRandomAESKey];
//            if(indexPath.section == 0){//授权二级锁主
//                [KLHelp showHUDAddedTo:self.view animated:YES];
//                [KLHttpAPI requestGetGrant_lock_priceWithCompletionHandler:^(MKNetworkOperation *operation) {
//                    [KLHelp hideAllHUDsForView:self.view animated:YES];
//                    NSLog(@"operation:%@",operation.responseString);
//                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
//                    if(isSuccess.integerValue == 1){
//                        NSString *price = [NSString stringWithFormat:@"价格:¥%@",[operation.responseJSON objectForKey:@"infor"]];
//                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"正在进行委托授权" message:price delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//                        alert.tag = 3;
//                        [alert show];
//                    }else{
//                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
//                    }
//                } errorHandler:^(NSString *error) {
//                }];
//            }
//            else if(indexPath.section == 1){//取消二级锁主授权
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"正在进行取消二级锁主操作！"
//                                                                message:@"危险操作，请谨慎！"
//                                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"朕意已决!" action:^{
//                    [KLHelp showHUDAddedTo:self.view animated:YES];
////                    [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:<#(NSString *)#> AESkey:<#(NSString *)#> type:<#(NSString *)#> apptime:<#(NSString *)#> command_code:<#(NSString *)#> begintime:<#(NSString *)#> endtime:<#(NSString *)#> style:<#(NSString *)#> completionHandler:<#^(MKNetworkOperation *operation)completionHandler#> errorHandler:<#^(NSString *error)errorHandler#>];
//                    [KLHttpAPI sendDelegateCommondWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text command_content:[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"] type:@"4" apptime:[HemaFunction getStringNow] commond_data:@"" totalfee:@"" completionHandler:^(MKNetworkOperation *operation) {
//                        NSLog(@"responseString:%@",operation.responseString);
//                        [KLHelp hideAllHUDsForView:self.view animated:YES];
//                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
//                    } errorHandler:^(NSString *error) {
//                    }];
//                }]
//                                                       otherButtonItems:[RIButtonItem itemWithLabel:@"以后再说!" action:nil], nil];
//                [alert show];
//            }
            if(indexPath.section == 0){//委托校时
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"委托他人帮助校时？"
                                                                message:nil
                                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil]
                                                       otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                    [KLHelp showHUDAddedTo:self.view animated:YES];
                    NSData *checkTimeData = [BuleFuction packageCheckTimeToDataWithRsaPublickey:rsaKey userAESKey:aesKey];
                    NSString *rsaPackage = [checkTimeData convertDataToHexStr:checkTimeData];
                    [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:rsaPackage AESkey:aesKey type:@"0" apptime:[HemaFunction getStringNow] command_code:@"c4" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:@"0" completionHandler:^(MKNetworkOperation *operation) {
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        NSLog(@"委托校时返回数据:%@",operation.responseString);
                        NSDictionary *dic = [operation responseJSON];
                        NSString *isSuccess = [dic objectForKey:@"success"];
                        if(isSuccess.integerValue == 1){
                            [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                        }else{
                            [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                        }
                    } errorHandler:^(NSString *error) {
                        [KLHelp showTextHUDforView:self.view text:error];
                    }];
                }], nil];
                [alert show];
            }else if(indexPath.section == 1){//委托设置黑名单
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入您想设置为黑名单用户的手机号" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                alert.tag = 1;
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alert show];
            }else if(indexPath.section == 2){//委托取消黑名单
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入您想取消黑名单用户的手机号" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                alert.tag = 2;
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alert show];
            }
        }else{
            if(indexPath.section == 0){//委托校时
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"委托他人帮助校时？"
                                                                message:nil
                                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil]
                                                       otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                    [KLHelp showHUDAddedTo:self.view animated:YES];
                    [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:@"" AESkey:@"" type:@"0" apptime:[HemaFunction getStringNow] command_code:@"c4" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:@"0" completionHandler:^(MKNetworkOperation *operation) {
                        NSLog(@"委托校时返回数据:%@",operation.responseString);
                        NSDictionary *dic = [operation responseJSON];
                        NSString *isSuccess = [dic objectForKey:@"success"];
                        if(isSuccess.integerValue == 1){
                            [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                        }else{
                            [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                        }
                    } errorHandler:^(NSString *error) {
                        [KLHelp showTextHUDforView:self.view text:error];
                    }];
                }], nil];
                [alert show];
            }else if(indexPath.section == 1){//委托设置黑名单
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入您想设置为黑名单用户的手机号" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                alert.tag = 1;
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alert show];
            }else if(indexPath.section == 2){//委托取消黑名单
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入您想取消黑名单用户的手机号" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                alert.tag = 2;
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alert show];
            }
        }
    }else{
        [JRToast showWithText:@"手机号格式有误！"];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 2;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 17)];
    header.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    return header;
}

#pragma mark - 主界面ui设置
-(void)mainUiSet{
    self.view.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    //头视图设置
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 140)];
    headView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headView;
    
    //输入委托人手机号的textfield
    self.delegatePhone = [[UITextField alloc]init];
    self.delegatePhone.placeholder = @"请输入受委托人手机号";
    self.delegatePhone.borderStyle = UITextBorderStyleRoundedRect;
    self.delegatePhone.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.delegatePhone.keyboardType = UIKeyboardTypeNumberPad;
    self.delegatePhone.adjustsFontSizeToFitWidth = YES;
    [headView addSubview:self.delegatePhone];
    [self.delegatePhone mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerX.equalTo(headView).offset(0);
        make.width.mas_equalTo(UI_View_Width-40);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(20);
    }];
    //点击选择指令起始时间
    self.beginTimeBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 80, (UI_View_Width-30)/2, 40)];
    [self.beginTimeBtn setTitle:@"命令起始时间" forState:UIControlStateNormal];
    self.beginTimeBtn.titleLabel.font = [UIFont systemFontOfSize:17 weight:0.5];
    [self.beginTimeBtn setTitleColor:RGB_UI_COLOR(8, 128, 181) forState:UIControlStateNormal];
    self.beginTimeBtn.layer.masksToBounds = YES;
    self.beginTimeBtn.layer.cornerRadius = 5;
    self.beginTimeBtn.layer.borderWidth = 2;
    self.beginTimeBtn.layer.borderColor = RGB_UI_COLOR(8, 128, 181).CGColor;
    [self.beginTimeBtn addTarget:self action:@selector(selectBeginTime:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.beginTimeBtn];
    //点击选择命令结束时间
    self.endTimeBtn = [[UIButton alloc]initWithFrame:CGRectMake(10+(UI_View_Width-30)/2+10, 80, (UI_View_Width-30)/2, 40)];
    [self.endTimeBtn setTitle:@"命令起始时间" forState:UIControlStateNormal];
    self.endTimeBtn.titleLabel.font = [UIFont systemFontOfSize:17 weight:0.5];
    [self.endTimeBtn setTitleColor:RGB_UI_COLOR(8, 128, 181) forState:UIControlStateNormal];
    self.endTimeBtn.layer.masksToBounds = YES;
    self.endTimeBtn.layer.cornerRadius = 5;
    self.endTimeBtn.layer.borderWidth = 2;
    self.endTimeBtn.layer.borderColor = RGB_UI_COLOR(8, 128, 181).CGColor;
    [self.endTimeBtn addTarget:self action:@selector(selectEndTime:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.endTimeBtn];
    
    //导航栏设置
    self.navigationController.navigationBarHidden = NO;
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 选择时间范围点击方法
-(void)selectBeginTime:(UIButton *)sender{
    [self.delegatePhone endEditing:YES];
    //选择起始日期
    NSLog(@"选择起始日期");
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithCompleteBlock:^(NSDate *startDate) {
        NSString *date = [startDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
        NSLog(@"时间： %@",date);
        [sender setTitle:date forState:UIControlStateNormal];
        self.beginTimeToLock = [startDate stringWithFormat:@"yyMMddHHmmss"];
    }];
    if(self.endTimeToLock != nil){
        NSDateFormatter *ft = [[NSDateFormatter alloc]init];
        [ft setDateFormat:@"yyyy-MM-dd HH:mm"];
        datepicker.maxLimitDate = [ft dateFromString:self.endTimeBtn.titleLabel.text];
    }
    datepicker.minLimitDate = [NSDate date];
    
    datepicker.datePickerStyle = DateStyleShowYearMonthDayHourMinute;
    [datepicker show];
}

-(void)selectEndTime:(UIButton *)sender{
    [self.delegatePhone endEditing:YES];
    //选择结束日期
    NSLog(@"选择结束日期");
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithCompleteBlock:^(NSDate *startDate) {
        NSString *date = [startDate stringWithFormat:@"yyyy-MM-dd HH:mm"];
        NSLog(@"时间： %@",date);
        [sender setTitle:date forState:UIControlStateNormal];
        self.endTimeToLock = [startDate stringWithFormat:@"yyMMddHHmmss"];
    }];
    if(self.beginTimeToLock != nil){
        NSDateFormatter *ft = [[NSDateFormatter alloc]init];
        [ft setDateFormat:@"yyyy-MM-dd HH:mm"];
        datepicker.minLimitDate = [ft dateFromString:self.beginTimeBtn.titleLabel.text];
    }else{
        datepicker.minLimitDate = [NSDate date];
    }
    datepicker.datePickerStyle = DateStyleShowYearMonthDayHourMinute;
    [datepicker show];
}

#pragma mark -alertView的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 1 && buttonIndex == 1){
        UITextField *tf=[alertView textFieldAtIndex:0];
        NSString *tf_text = tf.text;
        if(![HemaFunction xfunc_isMobileNumber:tf_text]){
            [KLHelp showTextHUDforView:self.view text:@"请输入手机号！"];
            return ;
        }
        if(self.isFirstMaster){
            NSString *rsaKey = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
            if(rsaKey == nil){
                [KLHelp showTextHUDforView:self.view text:@"锁公钥丢失，请重新扫描二维码!"];
                return ;
            }
            NSString *aesKey = [KLHelp getUserSixTeenRandomAESKey];
            NSData *settingBlackData = [BuleFuction packageSettingBlackUserWithPhone:tf_text psaPublicKey:rsaKey userAESKey:aesKey];
            NSString *rsaPackage = [settingBlackData convertDataToHexStr:settingBlackData];
            [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:rsaPackage AESkey:aesKey type:@"1" apptime:[HemaFunction getStringNow] command_code:@"c1" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:tf_text completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"委托设置黑名单返回数据:%@",operation.responseString);
                NSDictionary *dic = [operation responseJSON];
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                }else{
                    [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:error];
            }];
        }else{
            [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:@"" AESkey:@"" type:@"1" apptime:[HemaFunction getStringNow] command_code:@"c1" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:tf_text completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"委托设置黑名单返回数据:%@",operation.responseString);
                NSDictionary *dic = [operation responseJSON];
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                }else{
                    [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:error];
            }];
        }
    }else if (alertView.tag == 2 && buttonIndex == 1){
        UITextField *tf=[alertView textFieldAtIndex:0];
        NSString *tf_text = tf.text;
        if(![HemaFunction xfunc_isMobileNumber:tf_text]){
            [JRToast showWithText:@"请输入合法手机号"];
            return ;
        }
        if(self.isFirstMaster){
            NSString *rsaKey = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
            if(rsaKey == nil){
                [KLHelp showTextHUDforView:self.view text:@"锁公钥丢失，请重新扫描二维码!"];
                return ;
            }
            NSString *aesKey = [KLHelp getUserSixTeenRandomAESKey];
            NSData *settingBlackData = [BuleFuction packageCancelBlackUserWithPhone:tf_text psaPublicKey:rsaKey userAESKey:aesKey];
            NSString *rsaPackage = [settingBlackData convertDataToHexStr:settingBlackData];
            [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:rsaPackage AESkey:aesKey type:@"2" apptime:[HemaFunction getStringNow] command_code:@"c2" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:tf_text completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"委托取消黑名单返回数据:%@",operation.responseString);
                NSDictionary *dic = [operation responseJSON];
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                }else{
                    [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:error];
            }];
        }else{
            [KLHttpAPI sendCommondToLockWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text rsa:@"" AESkey:@"" type:@"2" apptime:[HemaFunction getStringNow] command_code:@"c2" begintime:self.beginTimeBtn.titleLabel.text endtime:self.endTimeBtn.titleLabel.text style:[self.currentLockInfo objectForKey:@"type"] set_mobile:tf_text completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"委托取消黑名单返回数据:%@",operation.responseString);
                NSDictionary *dic = [operation responseJSON];
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [KLHelp showTextHUDforView:self.tableView text:@"委托指令发送成功！"];
                }else{
                    [KLHelp showTextHUDforView:self.tableView text:[dic objectForKey:@"msg"]];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:error];
            }];
        }
    }else if (alertView.tag == 3 && buttonIndex == 1){
        totalfee = [alertView.message substringFromIndex:4];
        NSLog(@"totalfee:%@,%zd",totalfee,totalfee.length);
        //判断当前余额是否充足
        NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"];
        if(amount.doubleValue < totalfee.doubleValue){
            self.money = [NSString stringWithFormat:@"%.f",totalfee.doubleValue * 100];
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
            [sheet showInView:self.view];
            
            return ;
        }
        NSString *publicStr = [publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]];
        if(publicStr.length == 0){
            [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
            return ;
        }
        [KLHttpAPI sendDelegateCommondWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text command_content:[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"] type:@"3" apptime:[HemaFunction getStringNow] commond_data:[publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]] totalfee:totalfee completionHandler:^(MKNetworkOperation *operation) {
            NSLog(@"responseString:%@",operation.responseString);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
        } errorHandler:^(NSString *error) {
        }];
    }
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%zd",buttonIndex);
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        [KLHelp showHUDAddedTo:self.view animated:YES];
        //设置支付代理
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"localString:%@",locationString);
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK委托二级锁主在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0003%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];//商户自定义订单号
    payReq.billNo = self.trade_no;
    NSLog(@"trade_no:%@",self.trade_no);
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    [KLHelp hideAllHUDsForView:self.view animated:YES];
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    [KLHttpAPI sendDelegateCommondWithLock_id:[self.currentLockInfo objectForKey:@"id"] mobile:self.delegatePhone.text command_content:[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"] type:@"3" apptime:[HemaFunction getStringNow] commond_data:[publicKeysDic objectForKey:[self.currentLockInfo objectForKey:@"uname"]] totalfee:totalfee completionHandler:^(MKNetworkOperation *operation) {
                        NSLog(@"responseString:%@",operation.responseString);
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    } errorHandler:^(NSString *error) {
                    }];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"网络波动，充值失败"];
            }];
            
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
        }
    }
}

@end
